package com.iraeta.controller;

import com.alibaba.fastjson.JSON;
import com.iraeta.Config;
import com.iraeta.common.Result;
import com.iraeta.entity.main.SysFiles;
import com.iraeta.service.sys.ISysFilesService;
import com.iraeta.uitl.FileUploadUtils;
import com.iraeta.uitl.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/common")
public class CommonController extends BaseController{
    @Autowired
    Config config;
    @Autowired
    private ISysFilesService iSysFilesService;

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public String uploadFile(MultipartFile file) throws Exception{
        try {
            // 上传文件路径
            String filePath = config.profile;
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = this.getUrl() + fileName;

            //保存到表里面
            HttpServletRequest httpServletRequest = this.getRequest();
            int entityTypeId = httpServletRequest.getHeader("entityTypeId") == null ? 0 : Integer.parseInt(httpServletRequest.getHeader("entityTypeId"));
            long entityId = httpServletRequest.getHeader("entityId") == null ? 0 : Long.parseLong(httpServletRequest.getHeader("entityId"));
            SysFiles sysFiles = new SysFiles(entityTypeId, entityId, Util.getName(fileName), fileName);
            sysFiles.setCreateBy(String.valueOf(this.getUserId()) );
            iSysFilesService.insertSysFiles(sysFiles);

            Map<String,Object> ajax = new HashMap<>();
            ajax.put("fId", sysFiles.getfId());
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", Util.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return JSON.toJSONString(Result.success(ajax));
        }catch (Exception e){
            e.printStackTrace();
            return JSON.toJSONString(Result.error(e.getMessage()));
        }
    }

    private String getUrl() {
        HttpServletRequest request = this.getRequest();
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }

    @PostMapping("/deletefile/{id}")
    public String deleteFile(@PathVariable("id") Long id)
    {
        iSysFilesService.deleteSysFilesByFId(id);
        return  JSON.toJSONString(Result.success());
    }

    @GetMapping("/listfile/{tid}/{eid}")
    public String listFile(@PathVariable("tid") Integer tid, @PathVariable("eid") Long eid)
    {
        List<SysFiles> sysFiles = iSysFilesService.selectSysFilesList(tid, eid);
        return  JSON.toJSONString(Result.success(sysFiles));
    }

    @GetMapping("/getfile/{id}")
    public String getFile(@PathVariable("id") Long fId)
    {
        SysFiles sysFiles = iSysFilesService.selectSysFilesByFId(fId);
        return  JSON.toJSONString(Result.success(sysFiles));
    }
}
